package com.mysteel.testssoserver.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * ProjectName: mail
 * ClassName: LoginController
 * Description:
 * date: 2021/03/13/013 13:58
 *
 * @author xiaochao
 */
@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/login.html")
    public String toLogin(@RequestParam("redirect_url") String url, Model model, @CookieValue(name = "sso_token",required = false) Cookie tokenCookie){
        if (tokenCookie != null){
            // 用户已经登录过了
            return "redirect:" + url + "?token=" + tokenCookie.getValue();
        }
        model.addAttribute("url",url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(String username, String password, String url, HttpServletResponse response){
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)){
            // 保存登录成功的用户信息
            String key = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(key,username);
            // 留下cookie，证明浏览器访问过登录页面并登录成功过
            Cookie cookie = new Cookie("sso_token", key);
            response.addCookie(cookie);
            return "redirect:" + url + "?token=" + key;
        }
        // 登录失败，展示登录页
        return "redirect:http://ssoserver.com:8080/login.html?redirect_url=" + url;
    }

    @ResponseBody
    @GetMapping("/userInfo")
    public String queryUserInfo(String token){
        return redisTemplate.opsForValue().get(token);
    }
}
